package cn.easyplatform.studio.web.editors.admin;

import cn.easyplatform.studio.StudioApp;
import cn.easyplatform.studio.cmd.admin.GetLockMapCmd;
import cn.easyplatform.studio.cmd.admin.GetSessionManagerCmd;
import cn.easyplatform.studio.context.Contexts;
import cn.easyplatform.studio.dos.LockDo;
import cn.easyplatform.studio.interceptor.CommandContext;
import cn.easyplatform.studio.utils.WebUtils;
import cn.easyplatform.studio.vos.LoginUserVo;
import cn.easyplatform.studio.vos.LoginlogVo;
import cn.easyplatform.studio.web.controller.admin.LoginLogListener;
import cn.easyplatform.studio.web.editors.AbstractPanelEditor;
import cn.easyplatform.studio.web.layout.WorkbenchController;
import cn.easyplatform.type.StateType;
import org.zkoss.util.resource.Labels;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zk.ui.event.OpenEvent;
import org.zkoss.zul.*;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author Zeta
 * @Version 1.0
 */
public class UserManageEditor extends AbstractPanelEditor {

    public UserManageEditor(WorkbenchController workbench, String id) {
        super(workbench , id);
    }

    private Label userCount;
    private Button refresh;
    private Bandbox search;
    private Listbox userOnline;

    @Override
    public void create(Object... args) {
        Idspace is = createPanel(Labels.getLabel("menu.online.user.management"), "~./images/dictionary.png",
                "~./include/admin/usermanage.zul");

        this.userCount = (Label) is.getFellow("usermanage_lable_usercount");
        this.userOnline = (Listbox) is.getFellow("usermanage_listbox_userlist");
        search = (Bandbox) is.getFellow("usermanage_bandbox_search");
        search.addEventListener(Events.ON_OPEN, this);
        refresh = (Button) is.getFellow("usermanage_lable_refresh");
        refresh.addEventListener(Events.ON_CLICK, this);
        userOnline.addEventListener(Events.ON_CLICK, this);

        userCount.setValue(StudioApp.execute(new GetSessionManagerCmd()).getUsers().size() + "");

        List<LoginlogVo> list = changefield((List<LoginlogVo>) LoginLogListener.getAllOnlineUser());

        createList(list);

    }

    @Override
    protected void dispatch(Event evt) {
        if (evt.getTarget() == search) {
            OpenEvent oe = (OpenEvent) evt;
            String str = (String) oe.getValue();
            if(null==str||("").equals(str)){
                List<LoginlogVo> list = changefield((List<LoginlogVo>)LoginLogListener.getAllOnlineUser());
                userOnline.getItems().clear();
                createList(list);

            }else {
                List<LoginlogVo> list = changefield((List<LoginlogVo>) LoginLogListener.getOnlineUserByUserId(str));
                userOnline.getItems().clear();
                createList(list);
            }
        }
        if (evt.getTarget() == refresh) {
            List<LoginlogVo> list = changefield((List<LoginlogVo>)LoginLogListener.getAllOnlineUser());
            search.getChildren().clear();
            userOnline.getItems().clear();
            userCount.setValue(StudioApp.execute(new GetSessionManagerCmd()).getUsers().size() + "");
            createList(list);
        }
    }

    //改变集合字段
    public List<LoginlogVo> changefield (List<LoginlogVo> list){
        List<LoginlogVo> clist = new ArrayList<LoginlogVo>();
        if(null!=list && !list.isEmpty()){
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).getUserType().equals("0")) {
                    list.get(i).setUserType("用户");
                } else if (list.get(i).getUserType().equals("1")) {
                    list.get(i).setUserType("超级管理员");
                }
                clist.add(list.get(i));
            }
        }
        return clist;
    }

    //
    private EventListener el = new EventListener() {
        @Override
        public void onEvent(Event event) throws Exception {
            if (event.getTarget().getPreviousSibling() == null)
                onLock(event);
            else if (event.getTarget().getNextSibling() == null)
                onShowLog(event);
            else
                onStop(event);
        }
    };

    private void createList(List<LoginlogVo> list) {
        for(LoginlogVo s : list) {
            Listitem listitem = new Listitem();
            listitem.setValue(s);
            listitem.appendChild(new Listcell(s.getUserId()));
            listitem.appendChild(new Listcell(s.getUserName()));
            listitem.appendChild(new Listcell(s.getIpAddress()));
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String d = format.format(s.getLoginTime());
            listitem.appendChild(new Listcell(d));
            listitem.appendChild(new Listcell(s.getUserType()));
            listitem.appendChild(new Listcell(s.getRoleName()));
            listitem.appendChild(new Listcell(s.getLoginTN()));
            listitem.appendChild(new Listcell(s.getSession().getId()));

            Listcell listcell = new Listcell();
            Button op = new Button();
            if (4 == StateType.START) {
                op.setIconSclass("z-icon-cog z-icon-spin");
                op.setLabel(Labels.getLabel("admin.user.blocked"));
            } else if (3 == StateType.PAUSE) {
                op.setIconSclass("z-icon-lock");
                op.setLabel(Labels.getLabel("admin.user.running"));
            }
            op.setSclass("ml-2");
            op.addEventListener(Events.ON_CLICK, el);
            op.setParent(listcell);

            Button stop = new Button(Labels.getLabel("admin.user.remove"));
            stop.setIconSclass("z-icon-remove");
            stop.setSclass("ml-2");
            stop.addEventListener(Events.ON_CLICK, el);
            stop.setParent(listcell);

            Button log = new Button(Labels.getLabel("admin.user.real.log"));
            log.setIconSclass("z-icon-history");
            log.setSclass("ml-2");
            log.addEventListener(Events.ON_CLICK, el);
            log.setParent(listcell);
            listitem.appendChild(listcell);

            userOnline.appendChild(listitem);
        }

    }

    private void onShowLog(final Event evt) {
        final LoginlogVo vo = ((Listitem) evt.getTarget().getParent().getParent()).getValue();
        Map<String, Object> args = new HashMap<>();
        args.put("s", vo);
        Executions.createComponents("~./admin/log_dialog.zul", null, args);
    }

    private void onLock(final Event evt) {
        final LoginlogVo vo = ((Listitem) evt.getTarget().getParent().getParent()).getValue();

    }

    private void onStop(final Event evt) {
        final LoginlogVo vo = ((Listitem) evt.getTarget().getParent().getParent()).getValue();
        if (Contexts.getUser().getUserId().equals(vo.getUserId())) {
            WebUtils.showInfo(Labels.getLabel("admin.user.unself"));
        }else if(null == StudioApp.execute(new GetSessionManagerCmd()).getUser(vo.getUserId())||null==vo.getSession()){
            WebUtils.showInfo(Labels.getLabel("admin.user.remove.warning"));
        } else {
            System.out.println("连接池是否有该id："+StudioApp.execute(new GetSessionManagerCmd()).getUser(vo.getUserId()));
            System.out.println("是否可以获得该session："+vo.getSession());
            WebUtils.showConfirm(Labels.getLabel("admin.user.removes"), new EventListener<Event>() {
                public void onEvent(Event event) throws Exception {
                if (event.getName().equals(Events.ON_OK)) {
                    LoginLogListener.RemoveLog(vo);//记录用户退出
                    LoginUserVo user = (LoginUserVo) vo.getSession().getAttribute(Contexts.EP_USER);
                    StudioApp.execute(new GetSessionManagerCmd()).removeUser(user);
                    vo.getSession().removeAttribute(Contexts.EP_USER);
                    vo.getSession().removeAttribute(Contexts.EP_PROJECT);
                    vo.getSession().invalidate();
                    Map<String, LockDo> repo = StudioApp.execute(new GetLockMapCmd("ep_entity_lock"));
                    synchronized (repo) {
                        Iterator<LockDo> itr = repo.values().iterator();
                        StringBuilder sb = new StringBuilder();
                        while (itr.hasNext()) {
                            LockDo li = itr.next();
                            if (li.getUserId().equals(vo.getUserId())) {
                                sb.setLength(0);
                                sb.append(li.getProjectId()).append(":")
                                        .append(li.getEntityId());
                                repo.remove(sb.toString());
                            }
                        }
                        sb = null;
                    }
                    WebUtils.showInfo(Labels.getLabel("admin.user.remove.success"));
                    List<LoginlogVo> list = changefield((List<LoginlogVo>) LoginLogListener.getAllOnlineUser());
                    userOnline.getItems().clear();
                    userCount.setValue(StudioApp.execute(new GetSessionManagerCmd()).getUsers().size() + "");
                    createList(list);
                }

                }
            });
        }
    }
}


